#include "main.h"
int decompres (FILE * arc, FILE * fileToWrite, fileHead * fileHd)
{
	unsigned char buf_in[SIZE_BUF] = {0};
	unsigned char buf_out[SIZE_BUF] = {0};
	unsigned long long int count = fileHd->huff_file_len;
	int n = 1;
	int i = 0;
	int rc = 0;
	int count_2 = 0;
	int rc2 = NEW_DATA;
	str_inf_dec * inf_dec = (str_inf_dec*) calloc (1,sizeof(str_inf_dec));
	envInf.inf_2 = inf_dec;
	if (!inf_dec)	cl_exit (DECOMPRESS,MEMORY_ERR);
	rc = fread (buf_in,sizeof(char),fileHd->huff_block,arc);
	if (rc != fileHd->huff_block)	cl_exit (DECOMPRESS,READ_ERR);
	inf_dec->head = StrToHufTree (buf_in,fileHd->huff_block);
	inf_dec->elm = inf_dec->head;
	count -= fileHd->huff_block;
	if (fileHd->huff_ubits & _1_CHAR)	{
		rc = fread (buf_in,sizeof(char),1,arc);
		if (rc != 1)	cl_exit (DECOMPRESS,READ_ERR);
		count --;
		buf_out[0] = buf_in[0];
		rc = fread (buf_in,sizeof(char),count,arc);
		if (rc != count)	cl_exit (DECOMPRESS,READ_ERR);
		count = strToInt ((char*)buf_in,count);
		for (i = 0; i<count; i++)
		{
			rc = fwrite (buf_out,sizeof(char),1,fileToWrite);
			if (rc != 1)	cl_exit (DECOMPRESS,WRITE_ERR);
		}
		return 0;
	}
	count_2 = (count / SIZE_BUF) + 1;
	while (n == 1) {
		if (rc2 != NEW_BUF_OUT)	{
			memset (buf_in,0,SIZE_BUF);
			if (count>0)
				if (count/SIZE_BUF) {
					rc = fread (buf_in,sizeof(char),SIZE_BUF,arc);
					count -= SIZE_BUF;
					if (rc != SIZE_BUF)	cl_exit (DECOMPRESS,READ_ERR);
					inf_dec->max_pos = rc;
				}
				else {
					rc = fread (buf_in,sizeof(char),count,arc);
					if (rc != count) cl_exit (DECOMPRESS,READ_ERR);
					inf_dec->max_pos = rc;
					count = 0;
				}
			if (count_2>0)	count_2--;
			if (count_2 == 0)	inf_dec->u_bits = (fileHd->huff_ubits & 0x0F);
			inf_dec->cur_pos = 0;
			inf_dec->ind_bit = 0;
		}
		if (count > 0)	{
		rc2 = BitsInChar (buf_in,buf_out,inf_dec);
		if (rc2 != NEW_BUF_IN)	{
			rc = fwrite (buf_out,sizeof(char),inf_dec->ind_char,fileToWrite);
			if (rc != inf_dec->ind_char)	cl_exit (DECOMPRESS,WRITE_ERR);
			memset (buf_out,0,SIZE_BUF);
			inf_dec->ind_char = 0;
		}
		}	else	{
				rc2 = BitsInChar (buf_in,buf_out,inf_dec);
				if (rc2 != NEW_BUF_OUT)	{
					rc = fwrite (buf_out,sizeof(char),inf_dec->ind_char,fileToWrite);
					if (rc != inf_dec->ind_char) cl_exit (DECOMPRESS,WRITE_ERR);
					n = 0;
					break;
				}	
				else {
					rc = fwrite (buf_out,sizeof(char),SIZE_BUF,fileToWrite);
					if (rc != SIZE_BUF) cl_exit (DECOMPRESS,WRITE_ERR);
					memset (buf_out,0,SIZE_BUF);
					inf_dec->ind_char = 0;
				}
		}
	}
	return 0;
}

